<template>
  <p-modal
    v-if="visible"
    v-model="visible"
    :title="title"
    :mask-closable="false"
    style="height: 600px;"
    @cancel="handleCancel"
  >
    <p-form-model
      ref="fuleForm"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      :model="form"
      :rules="rules"
    >
      <div v-if="showDetail" class="view">
        <p-form-model-item label="国家" prop="">
          {{ form.country }}
        </p-form-model-item>
        <p-form-model-item label="省" prop="">
          {{ form.province }}
        </p-form-model-item>
        <p-form-model-item label="城市" prop="">
          {{ form.city }}
        </p-form-model-item>
        <p-form-model-item label="街道" prop="">
          <div class="item-box">
            {{ form.street }}
          </div>
        </p-form-model-item>
        <p-form-model-item label="邮政编码" prop="">
          {{ form.postalCode }}
        </p-form-model-item>
        <p-form-model-item label="详细地址" prop="">
          <div class="item-box">
            {{ form.address }}
          </div>
        </p-form-model-item>
        <p-form-model-item label="备注" prop="">
          <div class="item-box">
            {{ form.remark }}
          </div>
        </p-form-model-item>
      </div>
      <div v-else class="edit">
        <p-form-model-item label="国家" prop="country">
          <p-select
            :value="form.country"
            placeholder="请选择"
            :get-popup-container="triggerNode => triggerNode.parentNode || document.body"
            @change="handleSelectChange($event, 'country')"
          >
            <p-select-option
              v-for="item in countryOptions"
              :key="item.cn"
              :value="item.cn"
            >
              {{ item.cn }}
            </p-select-option>
          </p-select>
        </p-form-model-item>
        <p-form-model-item label="省" prop="province">
          <p-select
            :value="form.province"
            placeholder="请选择"
            :get-popup-container="triggerNode => triggerNode.parentNode || document.body"
            :disabled="isDisabledInfo"
            @change="provinceChange($event, 'province')"
          >
            <p-select-option
              v-for="item in provinceOptions"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </p-select-option>
          </p-select>
        </p-form-model-item>
        <p-form-model-item label="城市" prop="city">
          <p-select
            :value="form.city"
            placeholder="请选择"
            :get-popup-container="triggerNode => triggerNode.parentNode || document.body"
            :disabled="isDisabledInfo"
            @change="handleSelectChange($event, 'city')"
          >
            <p-select-option
              v-for="item in cityOptions"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </p-select-option>
          </p-select>
        </p-form-model-item>
        <p-form-model-item label="街道" prop="street">
          <p-textarea
            v-model="form.street"
            style="overflow-y: auto;"
            placeholder="请输入"
          />
        </p-form-model-item>
        <p-form-model-item label="邮政编码" prop="postalCode">
          <p-input
            v-model.number="form.postalCode"
            placeholder="请输入"
          />
        </p-form-model-item>
        <p-form-model-item label="详细地址" prop="address">
          <p-textarea
            v-model="form.address"
            style="overflow-y: auto;"
            placeholder="请输入"
            :auto-size="{ minRows: 2, maxRows: 2 }"
          />
          <!-- <div v-show="addressRutes.isShow" class="waring">{{ addressRutes.text }}</div> -->
        </p-form-model-item>
        <p-form-model-item label="备注" prop="remark">
          <p-textarea
            v-model="form.remark"
            placeholder="请输入"
            style="overflow-y: auto;"
            :auto-size="{ minRows: 2, maxRows: 2 }"
          />
          <div v-show="remarkRutes.isShow" class="waring">{{ remarkRutes.text }}</div>
        </p-form-model-item>
      </div>
    </p-form-model>

    <template v-if="showDetail" slot="footer">
      <div class="middle">
        <p-button key="submit" @click="handleCancel">返回</p-button>
      </div>
    </template>
    <template v-else slot="footer">
      <div class="middle">
        <p-button key="cancel" type="primary" @click="handleOkChange">保存</p-button>
        <p-button key="submit" @click="handleCancel">取消</p-button>
      </div>
    </template>
  </p-modal>
</template>

<script>
import {
  postAddressInsert,
  getCoutryList,
  getProvincesList,
} from '@/api/customerApi.js';
import mixinTable from '@/mixins/mixin-table.js';
// import { postCode } from '@/utils/decorator.js'

export default {
  components: {},
  mixins: [mixinTable],
  props: {
    code: {
      type: [String, Number],
      default: '',
    },
    visible: {
      type: Boolean,
      defalut: false,
    },
    formInfo: {
      type: Object,
      default: () => ({}),
    },
    title: {
      type: String,
      default: '新增地址',
    },
    showDetail: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      // addressRutes: {
      //   isShow: false,
      //   text: ''
      // },
      remarkRutes: {
        isShow: false,
        text: ''
      },
      labelCol: {
        span: 4,
      },
      wrapperCol: {
        span: 16,
      },
      form: {
        id: '',
        // customerCode: '',
        country: '',
        province: '',
        city: '',
        street: '',
        postalCode: '',
        address: '',
        remark: '',
      },
      countryOptions: [], // 国家
      provinceOptions: [], // 省份
      cityOptions: [],
      rules: {
        address: [
          {
            required: true,
            message: '请输入详细地址',
            trigger: 'blur',
          },
          {
            max: 255,
            message: '输入内容过长',
            trigger: 'blur',
          },
        ],
        country: [{ required: true, message: '请选择国家', trigger: 'change' }],
        province: [
          {
            required: true,
            message: '请选择省',
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (this.form.country !== '中国' || value) {
                callback();
              } else if (!value) {
                callback(new Error(rule.message));
              }
            },
          },
        ],
        city: [
          {
            required: true,
            message: '请选择城市',
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (this.form.country !== '中国' || value) {
                callback();
              } else if (!value) {
                callback(new Error(rule.message));
              }
            },
          },
        ],
        postalCode: [
          {
            required: false,
            message: '邮政编码格式不正确',
            trigger: 'blur',
            // validator: postCode.bind(this)
            pattern: /^[1-9][0-9]{5}$/
          },
        ],
        street: [
          {
            required: false,
            max: 255,
            message: '输入内容过长',
            trigger: 'blur',
          },
        ],
      },
    };
  },
  computed: {
    isDisabledInfo() {
      return this.form.country !== '中国';
    },
  },
  watch: {
    formInfo: {
      async handler(val) {
        if (val) {
          this.form.id = val.id || '';
          // (this.form.customerCode = val.code),
          this.form.country = val.country;
          this.form.province = val.province;
          this.form.city = val.city;
          this.form.street = val.street;
          this.form.address = val.address;
          this.form.remark = val.remark;
          this.form.postalCode = val.postalCode;
          await this.getCoutryInfoList();
          await this.getProvincesList();
          await this.provinceChange(val.province, 'edit');
        }
      },
      deep: true,
      immediate: true,
    },
    // 'form.address': {
    //   handler(val) {
    //     if (!val || val.length < 255) {
    //       this.addressRutes.isShow = false
    //       this.addressRutes.text = ''
    //     }
    //     if (val.length > 255) {
    //       this.addressRutes.isShow = true
    //       this.addressRutes.text = '输入内容过长'
    //     }
    //   },
    //   deep: true,
    // },
    'form.remark': {
      handler(val) {
        if (!val || val?.length < 255) {
          this.remarkRutes.isShow = false
          this.remarkRutes.text = ''
        }
        if (val?.length > 255) {
          this.remarkRutes.isShow = true
          this.remarkRutes.text = '输入内容过长'
        }
      },
      deep: true,
    },
    // visible: {
    //   async handler(val) {
    //     if (val) {
    //       await this.getCoutryInfoList();
    //       await this.getProvincesList();
    //       await this.provinceChange(val.province, 'edit')
    //     }
    //   },
    //   deep: true,
    //   immediate: true,
    // },
  },
  created() {
    // this.getCoutryInfoList();
    // this.getProvincesList();
  },
  methods: {
    async handleOkChange() {
      const valid = this.validate();
      const data = this.form;
      if (this.form.remark && this.form.remark?.length > 255) {
        this.$message.error('备注输入内容过长');
        return;
      }
      if (!valid) return new Promise(() => {});
      
      if (valid) {
        const result = await postAddressInsert({
          ...data,
          customerCode: this.code,
        });
        if (result?.data?.code === 0) {
          this.$message.success('保存成功！');
          this.handleCancel();
          this.$emit('change');
        }
      }
    },
    handleCancel() {
      this.$emit('update:visible', false);
    },
    async getCoutryInfoList() {
      const res = await getCoutryList();
      const data = res?.data?.data;
      // console.log(data,'op');
      this.countryOptions = data || [];
    },
    async getProvincesList() {
      const res = await getProvincesList();
      const data = res?.data?.data;
      this.provinceArr = data || [];
      let val = data?.map(item => {
        return {
          value: item.name,
          label: item.name,
        };
      });
      this.provinceOptions = val || [];
    },
    // 选中值
    handleSelectChange(val, key) {
      this.form[key] = val;
      if (key === 'country' && val !== '中国') {
        this.form.province = '';
        this.form.city = '';
      }
    },
    provinceChange(value, key) {
      console.log(value, key);
      this.form.province = value;
      if (key === 'province') {
        this.form.city = '';
      }
      let data = this.provinceArr?.find(item => {
        return item.name === value;
      });
      let city = data?.city?.map(item => {
        return {
          value: item.name,
          label: item.name,
        };
      });
      this.cityOptions = city || [];
    },
    validate() {
      let validate = false;
      this.$refs.fuleForm.validate(valid => {
        validate = valid;
      });
      return validate;
    },
  },
};
</script>

<style lang="less" scoped>
.middle {
  display: flex;
  justify-content: center;
}
.waring {
  position: absolute;
  top: 18px;
  left: 0px;
  height: 14px;
  color: red;
  font-size: 12px;
  font-weight: 400;
}
.item-box {
  height: 100px;
  overflow: scroll;
}
</style>
